package com.ita.controller;

import java.io.IOException;
import java.nio.channels.SeekableByteChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.ita.util.Constant;

@Controller(value = "myWsHandler")
@RequestMapping("/ws/manage")
public class MyWsHandler extends TextWebSocketHandler {

	private static Map<String, WebSocketSession> sens = new HashMap<String, WebSocketSession>();

	private static AtomicInteger onlineCount = new AtomicInteger(0);

	public void handleTextMessage(WebSocketSession session, TextMessage message) {

		System.out.println("text message: " + session.getId() + "-" + message.getPayload());
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		// 与客户端完成连接后调用
		System.out.println("afterConnectionEstablished");
		System.out.println("getId:" + session.getId());
		System.out.println("getLocalAddress:" + session.getLocalAddress().toString());
		System.out.println("getTextMessageSizeLimit:" + session.getTextMessageSizeLimit());
		System.out.println("getUri:" + session.getUri().toString());
		System.out.println("getPrincipal:" + session.getPrincipal());
		System.out.println("id: " + getClientId(session));

		String mid = getClientId(session);

		if (mid != null) {
			sens.put(mid, session);
			session.sendMessage(new TextMessage("你好".getBytes()));
			addOnlineCount();
		}

	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		// 消息传输出错时调用
		System.out.println("handleTransportError");
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		// 一个客户端连接断开时关闭
		System.out.println("afterConnectionClosed");
		sens.remove(session.getId());
		subOnlineCount();
	}

	@Override
	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return false;
	}

	public static void sendMessage(String sessionId, TextMessage message) {
		System.out.println("res id:" + sessionId);
		WebSocketSession session = sens.get(sessionId);
		// session.sendMessage(message);
		if (session != null && session.isOpen()) {
			try {
				session.sendMessage(message);
				// sens.get(sessionId).sendMessage(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// }

	}

	public static int getOnlineCount() {
		return onlineCount.get();
	}

	private void addOnlineCount() {
		onlineCount.getAndIncrement();
	}

	private void subOnlineCount() {
		onlineCount.getAndDecrement();
	}

	/**
	 * 获取用户标识
	 * 
	 * @param session
	 * @return
	 */
	private String getClientId(WebSocketSession session) {
		try {
			String clientId = (String) session.getAttributes().get(Constant.CLIENT_ID);
			return clientId;
		} catch (Exception e) {
			return null;
		}
	}
}
